package com.secsbrain.cmdb.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.secsbrain.cmdb.biz.IAppSystemService;
import com.secsbrain.cmdb.biz.IAppTypeService;
import com.secsbrain.cmdb.remote.SsoRemoteService;
import com.secsbrain.common.ResponseResult;
import com.secsbrain.common.utils.RedisUtil;
import com.secsbrain.sso.core.SsoHelper;
import com.secsbrain.sso.model.dto.system.UserDetailDTO;
import com.secsbrain.sso.model.dto.system.UserSimpleDTO;
import com.secsbrain.cmdb.dal.model.AppType;
import com.secsbrain.cmdb.dal.model.Host;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.plugins.Page;
import com.secsbrain.cmdb.biz.impl.CommonService;
import com.secsbrain.cmdb.biz.utils.ExcelReadUtil;
import com.secsbrain.common.ErrorCodeEnum;
import com.secsbrain.cmdb.client.model.App;
import com.secsbrain.cmdb.client.model.SystemTypeEnums;
import com.secsbrain.cmdb.dal.model.AppSystem;

/**
 * 应用系统控制层
 * @author zhaoyi
 *
 */
@RestController
@RequestMapping("api/appSystem")
public class AppSystemController{
	
    private static final Logger logger = LoggerFactory.getLogger(AppSystemController.class);
	
    @Autowired
    IAppSystemService appSystemService;
    
    @Autowired
    IAppTypeService appTypeService;
    
    @Autowired
    CommonService commonService;
    
    @Autowired
	SsoRemoteService userServiceFacade;
    
    /**
     * 功能描述: <br>
     * 查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseResult<?> queryList(Integer page, Integer limit,AppSystem params) {
    	if("".equals(params.getName())){
    		params.setName(null);
    	}
    	if("".equals(params.getLevel())){
    		params.setLevel(null);
    	}
    	if("".equals(params.getSystemType())){
    		params.setSystemType(null);
    	}
    	Page<AppSystem> pageBean=new Page<>(page, limit);
    	Page<AppSystem> result=appSystemService.queryAppSystemPageList(pageBean, params,null);
    	Map<Long, AppType> appTypeMap=appTypeService.getAllAppType();
    	Map<Long, Host> hostMap=commonService.getHostMap();
    	for(AppSystem appSystem:result.getRecords()){
    		if(appSystem.getQualityId()==0){
    			appSystem.setQualityId(null);
    		}
    		appSystem.setHostNames(getHostName(appSystem.getHostIds(), hostMap));
    		appSystem.setTypeName(appTypeMap.get(appSystem.getTypeId()).getName());
    	}
    	return new ResponseResult<>(result);
    }
    
    /**
     * 功能描述: <br>
     * 查询开发者列表
     *
     * @return
     */
    @RequestMapping(value = "/devList", method = RequestMethod.GET)
    public ResponseResult<?> queryDevList() {
		ResponseResult<List<UserSimpleDTO>> result=userServiceFacade.getDevelopers();
    	if(result.getCode()==1){
    		List<UserSimpleDTO> userSimpleList=result.getData();
        	return new ResponseResult<>(userSimpleList);
    	}else{
    		logger.error("请求开发者接口失败："+result.getMsg());
			return new ResponseResult<>(ErrorCodeEnum.ERROR_COMMON_PARAM.getCode(), result.getMsg());
    	}
    	
    }
    
    private String getHostName(String ids,Map<Long, Host> hostMap){
    	if(StringUtils.isEmpty(ids)){
    		return "";
    	}
    	List<Long> hostIds=new ArrayList<Long>();
    	if(ids.indexOf(",")!=-1){
    		for(String id:ids.split(",")){
        		hostIds.add(Long.parseLong(id));
    		}
    	}else{
    		hostIds.add(Long.parseLong(ids));
    	}
    	
    	StringBuilder stringBuilder=new StringBuilder();

    	for(Long hostId:hostIds){
    		stringBuilder.append(hostMap.get(hostId).getHostName()+",");
    	}
		return stringBuilder.deleteCharAt(stringBuilder.length()-1).toString();
    }
    
    private String getDevName(String ids){
    	if(StringUtils.isEmpty(ids)){
    		return "";
    	}
    	List<Long> userIds=new ArrayList<Long>();
    	if(ids.indexOf(",")!=-1){
    		for(String id:ids.split(",")){
        		userIds.add(Long.parseLong(id));
    		}
    	}else{
    		userIds.add(Long.parseLong(ids));
    	}
    	
    	Long[] userIdArry = (Long[])userIds.toArray(new Long[userIds.size()]);
		ResponseResult<List<UserDetailDTO>> result=userServiceFacade.getUserDTOByIds(userIdArry);
    	if(result.getCode()!=1){
    		logger.error("请求批量获取用户详情接口失败："+result.getMsg());
    		throw new RuntimeException(result.getMsg());
    	}
    	List<UserDetailDTO> list=result.getData();
    	if(CollectionUtils.isEmpty(list)){
    		return null;
    	}
    	if(list.size()==1){
    		return list.get(0).getNickname();
    	}
    	StringBuilder stringBuilder=new StringBuilder();
    	for(UserDetailDTO userDTO:list){
    		stringBuilder.append(userDTO.getNickname()+",");
    	}
		return stringBuilder.deleteCharAt(stringBuilder.length()-1).toString();
    }
    
    /**
     * 功能描述: <br>
     * 新增
     *
     * @param appSystem
     * @return
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public ResponseResult<?> insert(@RequestBody AppSystem appSystem) {
		appSystem.setName(appSystem.getName().trim());
    	appSystem.setCreateTime(new Date());
    	appSystem.setCreator(SsoHelper.currentUser().getNickname());
    	appSystem.setDevelopNames(getDevName(appSystem.getDevelopIds()));
    	appSystem.setOwnerName(getDevName(appSystem.getOwnerId()+""));
    	if(appSystem.getQualityId()!=null){
        	appSystem.setQualityName(getDevName(appSystem.getQualityId()+""));
    	}
    	appSystemService.insertSelective(appSystem);
    	
     	RedisUtil.remove(App.APP_REDIS_KEY);

    	return new ResponseResult<>();
    }
    
    /**
     * 功能描述: <br>
     * 更新
     *
     * @param appSystem
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public ResponseResult<?> update(@RequestBody AppSystem appSystem) {
		appSystem.setName(appSystem.getName().trim());
		appSystem.setUpdateTime(new Date());
    	appSystem.setUpdator(SsoHelper.currentUser().getNickname());
    	appSystem.setDevelopNames(getDevName(appSystem.getDevelopIds()));
    	appSystem.setOwnerName(getDevName(appSystem.getOwnerId()+""));
    	if(appSystem.getQualityId()!=null){
        	appSystem.setQualityName(getDevName(appSystem.getQualityId()+""));
    	}
    	appSystemService.updateSelectiveById(appSystem);
     	RedisUtil.remove(App.APP_REDIS_KEY);

    	return new ResponseResult<>();
    }
    
    /**
     * 功能描述: <br>
     * 删除
     *
     * @param appSystem
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public ResponseResult<?> delete(@RequestBody AppSystem appSystem) {
    	appSystemService.deleteById(appSystem.getId());
     	RedisUtil.remove(App.APP_REDIS_KEY);

    	return new ResponseResult<>();
    }
    
    /**
     * 功能描述: <br>
     * 应用类型
     *
     * @return
     */
    @RequestMapping(value = "types", method = RequestMethod.GET)
    public ResponseResult<?> appTypes() {
        return new ResponseResult<>(SystemTypeEnums.values());
    }
    
    @RequestMapping(value = "initAppSystem", method = RequestMethod.GET)
    public ResponseResult<?> initAppSystem() throws FileNotFoundException{
		ResponseResult<List<UserSimpleDTO>> userVo=userServiceFacade.getDevelopers();
    	List<UserSimpleDTO> userList=userVo.getData();
    	Map<String, Long> nameIdMap=new HashMap<String, Long>();
    	for(UserSimpleDTO userSimpleDTO:userList){
    		nameIdMap.put(userSimpleDTO.getNickname(), userSimpleDTO.getId());
    	}
    	
    	Map<String, Long> typeNameIdMap=new HashMap<String, Long>();
    	List<AppType> appTypeList=appTypeService.selectList(new AppType());
    	for(AppType appType:appTypeList){
    		typeNameIdMap.put(appType.getDepartment(), appType.getId());
    	}
    	
		List<AppSystem> appSystemList=new ArrayList<AppSystem>();

    	InputStream fis = new FileInputStream(new File("/opt/集群信息整理.xlsx"));
		List<String[]> cells = ExcelReadUtil.getAllExcelInfo(fis,false, null, null, "2", null, 0);
		for (int j = 0; j < cells.size(); j++) {
			AppSystem appSystem=new AppSystem();
			String appName=cells.get(j)[0];
			appSystem.setName(appName);
			if(StringUtils.isEmpty(appName)){
				continue;
			}
			String comment=cells.get(j)[1];
			appSystem.setComment(comment);
			String level=cells.get(j)[2];
			appSystem.setLevel(level);
			String systemType=cells.get(j)[3];
			if("SPRINGBOOT".equals(systemType)){
				systemType="BOOT";
			}
			appSystem.setSystemType(systemType);
			String ownerName=cells.get(j)[5];
			appSystem.setOwnerName(ownerName);
			//ownerId
			appSystem.setOwnerId(nameIdMap.get(ownerName));

			String gitUrl=cells.get(j)[9];
			appSystem.setGitUrl(gitUrl);
			String bType=cells.get(j)[10];
			if(StringUtils.isEmpty(bType)){
				continue;
			}
			String typeName="";
			if("中间件".equals(bType)){
				typeName="PUB";
			}else if("开课啦".equals(bType)){
				typeName="KKL";
			}else if("新航线".equals(bType)){
				typeName="XHX";
			}else if("大数据".equals(bType)){
				typeName="PUB";
			}else{
				typeName="PUB";
			}
			//typeId
			appSystem.setTypeId(typeNameIdMap.get(typeName));
			
			appSystem.setCreateTime(new Date());
			appSystem.setCreator("赵毅");
			appSystem.setQualityId(0L);
			appSystem.setQualityName("");
			appSystem.setHostIds("");
			appSystem.setHostNames("");
			appSystem.setRedis("");
			appSystem.setUpdator("");
			appSystem.setUpdateTime(new Date());
			appSystem.setPorts("");
			appSystem.setDevelopIds("");
			appSystem.setDevelopNames("");
			appSystemList.add(appSystem);
		}
		appSystemService.insertBatch(appSystemList);
        return new ResponseResult<>();
    }
    
    
}
